import { useState, forwardRef, useEffect } from 'react';
import { useForm } from '@formily/react';
import { Select } from 'antd';
import { useQueryFields } from '@inbiz/hooks';

// type IProps = {
//   callBackEvents?: { [key: `on${string}`]: Function }
//   emit?: (type: any, ...arg: any) => void
// } & typeof defaultProps

type IOptions = {
  value: string;
  label: string;
};
const { Option } = Select;
const MyAutoComplete = (props: any) => {
  // 准备数据
  const form = useForm();
  const sourceModel = form.query('form.senior.soure.x-component-props.sourceModel').take()! as {
    value: string;
  };

  const [refresh, $refresh] = useState(() => Date.now());
  useEffect(() => {
    $refresh(props.update);
  }, [props.update]);
  // result[0]：所有字段
  // result[1]: 是否还在加载  true为正在加载  false为加载完成
  const [fieldList, loadding] = useQueryFields(
    {
      key: sourceModel?.value,
      //@ts-ignore
      appId: form.appInfo.appId,
    },
    [props.update],
  );

  const [options, setOptions] = useState<IOptions[]>([]);

  useEffect(() => {
    if (!fieldList?.length) {
      return;
    }
    let nowOptions: IOptions[] = [];
    fieldList.forEach((item) => {
      nowOptions.push({ value: item.value, label: item.label });
    });
    setOptions(nowOptions);
  }, [loadding]);

  return (
    <Select {...props} showSearch>
      {options.map((item, i) => {
        return (
          <Option value={item.value} key={i}>
            {item.label}
          </Option>
        );
      })}
    </Select>
  );
};

export default MyAutoComplete;
